#!/usr/bin/env node

import { execSync } from 'child_process';
import fs from 'fs';
import path from 'path';

console.log('🧪 测试多环境配置...\n');

const environments = ['development', 'test', 'pre', 'production'];

// 检查环境文件是否存在
console.log('📁 检查环境文件:');
environments.forEach(env => {
  const envFile = `.env.${env}`;
  const exists = fs.existsSync(envFile);
  console.log(`  ${exists ? '✅' : '❌'} ${envFile}`);
});

console.log('\n🔧 测试构建命令:');

// 测试不同环境的构建
environments.forEach(env => {
  try {
    console.log(`\n📦 构建 ${env} 环境...`);
    const startTime = Date.now();
    
    const buildCmd = env === 'development' ? 'build:dev' : env === 'production' ? 'build' : `build:${env}`;
    execSync(`npm run ${buildCmd}`, {
      stdio: 'pipe',
      cwd: process.cwd()
    });
    
    const duration = Date.now() - startTime;
    console.log(`  ✅ ${env} 环境构建成功 (${duration}ms)`);
    
    // 检查构建产物
    const distExists = fs.existsSync('dist');
    console.log(`  📁 构建产物: ${distExists ? '✅' : '❌'}`);
    
  } catch (error) {
    console.log(`  ❌ ${env} 环境构建失败:`, error.message);
  }
});

console.log('\n🚀 测试开发服务器:');

// 测试开发环境启动
try {
  console.log('启动开发服务器...');
  const child = execSync('npm run dev', {
    stdio: 'pipe',
    cwd: process.cwd(),
    timeout: 5000
  });
  console.log('✅ 开发服务器启动成功');
} catch (error) {
  if (error.message.includes('timeout')) {
    console.log('✅ 开发服务器启动成功 (超时正常)');
  } else {
    console.log('❌ 开发服务器启动失败:', error.message);
  }
}

console.log('\n✨ 环境配置测试完成！');
console.log('\n📋 可用命令:');
console.log('  npm run dev          - 开发环境');
console.log('  npm run dev:test     - 测试环境开发');
console.log('  npm run dev:pre      - 预发布环境开发');
console.log('  npm run dev:prod     - 生产环境开发');
console.log('  npm run build        - 生产环境构建');
console.log('  npm run build:test   - 测试环境构建');
console.log('  npm run build:pre    - 预发布环境构建');
console.log('  npm run build:dev    - 开发环境构建');
